import httplib
from urlparse import urlparse
from communicator.models import User
import settings

openid_args = {
        'openid.ns': 'http://specs.openid.net/auth/2.0',
        'openid.ns.pape': 'http://specs.openid.net/extensions/pape/1.0',
        'openid.ns.max_auth_age': '300',
        'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select',
        'openid.identity': 'http://specs.openid.net/auth/2.0/identifier_select',
        'openid.return_to': 'http://%s:%d/login' % (settings.HOSTNAME, settings.PORT),
        'openid.realm': 'http://%s:%d/' % (settings.HOSTNAME, settings.PORT),
        'openid.assoc_handle': '33xx44pp55uu',
        'openid.mode': 'checkid_setup',
        'openid.ui.ns': 'http://specs.openid.net/extensions/ui/1.0',
        'openid.ui.mode': 'popup',
        'openid.ax.mode': 'fetch_request',
        'openid.ns.ax': 'http://openid.net/srv/ax/1.0',
        'openid.ax.type.email': 'http://axschema.org/contact/email',
        'openid.ax.required': 'email'
}

def send_post(url, params):
    host, path = urlparse(url)[1:3]
    connection = httplib.HTTPConnection(host, None, timeout=10)
    headers = {
        'Content-length': 0,
        'Accept': 'application/xrds+xml'
    }
    options = '?'
    for key in params.keys():
        options += '%s=%s&' % (key, params[key])
    try:
        connection.request("POST", path + options, None, headers)
        response = connection.getresponse()
        print response.status, response.reason
        return response
    except IOError as err:
        print err.strerror
    finally:
        connection.close()

def get_param(request, key):
    return request.REQUEST.get(key, None)

def get_user_id(request):
    return request.session.get('user_id')

def set_user_id(request, user_id):
    request.session['user_id'] = user_id

def get_current_user(request):
    user_id = get_user_id(request)
    return User.objects.get(id=user_id)